package org.zf.database.consts;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.util.EnumUtil;
import lombok.Getter;

import java.util.Map;

/**
 * 数据库类型与JDBC driver 映射
 */
@Getter
public enum DBType
{
    ORACLE("ORACLE", "oracle.jdbc.driver.OracleDriver", "jdbc:oracle"),
    SQLSERVER("SQLSERVER", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "jdbc:sqlserver"),
    MYSQL("MYSQL", "com.mysql.jdbc.Driver", "jdbc:mysql"),
    DB2("DB2", "com.ibm.db2.jcc.DB2Driver", "jdbc:db2"),
    POSTGRESQL("POSTGRESQL", "org.postgresql.Driver", "jdbc:postgresql"),
    DAMENG("DAMENG", "dm.jdbc.driver.DmDriver", "jdbc:dm");
    private final String dbName;
    private final String driverClass;
    private final String urlPrefix;

    DBType(String dbName, String driverClass, String urlPrefix)
    {
        this.dbName = dbName;
        this.driverClass = driverClass;
        this.urlPrefix = urlPrefix;
    }

    public static DBType parseJdbcUrl(String url, Object... objs) throws RuntimeException
    {
        return parseDb(url.split(":", 3)[1]);
    }

    public static DBType parseDb(String dbName) throws RuntimeException
    {
        Map<String, DBType> enumMap = EnumUtil.getEnumMap(DBType.class);
        for (DBType value : enumMap.values())
        {
            if (value.getDbName().equalsIgnoreCase(dbName))
                return value;
        }
        throw new BeanException("不支持的数据库类型：" + dbName);
    }
}
